//Эта переменная говорит о том, что файл загружен браузером.
var ergoLoaded = true;

var ERGOPrice;
var ERGOPriceDiscount;
var ERGONotes = "";
var ERGOInfo = {
	name: "Эрго Русь",
	price: 0,
	discountPrice: 0,
	rating: 0,
	notesToDisplay: new Array(0),
	notesSpecial: '',
	notes: "",
	realFr: 0,
	frArray: new Array(0),
	countSpecialNotes: 0,
	calc: function () {
		calculateERGO();
	}
};
var ERGOunableTocalculate = false;
var ERGONotesIndefinite = "";
var ergoXML;



function calculateERGO() {
	ERGOPrice = 0;
	if (typeof(ergoXML) == 'undefined') {
		$.ajax({
			url: "ergo/ergo_cars.xml?" + rand % 1000,
			success: function (response) {
				ergoXML = response;
				calcErgo(response);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				calculateERGO()
			}
		})
	} else {
		calcErgo(ergoXML);
	}
}

function calcErgo(response) {
	//	alert('1bt='+bt+'kAge'+kAge+'kExp='+kExp+'fr='+fr+'malus='+malus+'stoa='+stoa+'helm='+helm+'oplata='+oplata+'\nergoprice='+ERGOInfo.price);
	try {
		//	city=$('input:checked').filter('[name=town]').val();
		ERGOInfo.countSpecialNotes = 0;
		var xml = $(response);
		var carXML = xml.find("carList").eq(0);
		var xmlK = xml.find("Ki");
		var xmlJur = xml.find("Ki>juristic").eq(0);
		var Ki;
		var specialNotesTMP = '';
		var bt;
		var alarm;
		var fr;
		var realFr;
		var oplata;
		var kExp = 0;
		var kAge = 0;
		var countDrivers;
		ERGOInfo.notesToDisplay = new Array(0);
		ERGOInfo.notesSpecial = '';
		//   находим машину в xml
		if (carXML.find("m>n").filter(function () {
			return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
		}).length != 0) if (carXML.find("m>n").filter(function () {
			return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
		}).parent().find("c>n").filter(function () {
			return $(this).text().toUpperCase() == carName.toUpperCase()
		}).length != 0) {
			carXML = carXML.find("m>n").filter(function () {
				return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
			}).parent().find("c>n").filter(function () {
				return $(this).text().toUpperCase() == carName.toUpperCase()
			}).parent();
		} else if (carXML.find("m>n").filter(function () {
			return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
		}).parent().find("c>n").filter(function () {
			return $(this).text() == "*"
		}).length != 0) {
			carXML = carXML.find("m>n").filter(function () {
				return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
			}).parent().find("c>n").filter(function () {
				return $(this).text() == "*"
			}).parent();
		} else {
			carXML = carXML.find("m>n").filter(function () {
				return $(this).text() == "*"
			}).parent().find("c>n").filter(function () {
				return $(this).text() == "*"
			}).parent();
		} else {
			carXML = carXML.find("m>n").filter(function () {
				return $(this).text() == "*"
			}).parent().find("c>n").filter(function () {
				return $(this).text() == "*"
			}).parent();
		}
		carXML = carXML.find(city);
		var group = carXML.find('g');
		if (group.length == 0 /*|| $("#corporatePerson").attr('checked')*/ ) {
			ERGOInfo.price = parseInt('a');
			ERGOInfo.discountPrice = parseInt('a');
			counterCasco();
			return;
		} else
		group = parseInt(group.text());
	} catch (eee) {
		alert(eee)
	};

	var minT = carXML.find('min').length == 1 ? parseFloat(carXML.find('min').text()) : 2.5;
	var grH = carXML.find('h').length == 1 ? parseInt(carXML.find('h').text()) : 0;
	var age = "a" + carAge.replace("carAge", "");
	if ($("#naturalPerson").attr('checked')) { //	Расчет для физических лиц
		if (rus) { // Базовый тариф
			bt = xmlK.find("bt>" + city + ">rus>p>v").filter(function () {
				return $(this).text() == "g" + group
			}).eq(0).parent();
			bt = bt.find(age).eq(0);
		} else {
			bt = xmlK.find("bt>" + city + ">g" + group + ">p>v").filter(function () {
				return parseInt($(this).text()) >= parseInt(price)
			}).first();
			if (bt.length == 0) bt = xmlK.find("bt>" + city + ">g" + group + ">p>v").filter(function () {
				return $(this).text() == '*'
			}).first();
		}
		bt = bt.parent().find(age);
		bt = parseFloat(bt.text());
		if (!rus) { // Франшиза для иностранных ТС
			fr = xmlK.find("fr>" + city + ">p>v").filter(function () {
				return parseInt($(this).text()) >= parseInt(price)
			}).first().parent();

			if (fr.length == 0) fr = xmlK.find("fr>" + city + ">p>v").filter(function () {
				return $(this).text() == '*';
			}).parent();
			fr = fr.find('c').filter(function () {
				return parseInt($(this).find('fV').text()) <= selectedFr;
			}).last();
			if (fr.length == 1) {
				ERGOInfo.realFr = parseInt(fr.find('fV').eq(0).text());
				fr = parseFloat(fr.find('k').text());
			} else {
				ERGOInfo.realFr = 0;
				fr = 1;
			}
		} else { // Франшиза для отечественных ТС
			fr = xmlK.find('fr>' + city + '>rus>c').filter(function () {
				return parseInt($(this).find('fV').text()) <= selectedFr;
			}).last();
			if (fr.length == 1) {
				ERGOInfo.realFr = parseInt(fr.find('fV').eq(0).text());
				fr = parseFloat(fr.find('k').text());
			} else {
				ERGOInfo.realFr = 0;
				fr = 1;
			}
		}
		//		alert("fr="+fr+'\nRealFr='+ERGOInfo.realFr);
		//		alert(ERGOInfo.fr);
		//	Возраст/стаж водителей
		try {
			if (driversListForCalc.length > 5) countDrivers = "M5";
			else
			countDrivers = "L6";
			if (city == 'spb') { // Санкт=Петербург
				if (multiDrive) {
					kAge = parseFloat(xmlK.find('drAge>spb>M5>c').filter(function () {
						return $(this).find('a').text() == '18-21'
					}).find('v').eq(0).text());
					kExp = parseFloat(xmlK.find('drExp>spb>c').filter(function () {
						return $(this).find('a').text() == '0-1'
					}).find('v').eq(0).text());
				} else {
					var t, drA, drE;
					for (var i = 0; i < driversListForCalc.length; i++) {
						var drA = driversListForCalc.eq(i).find('.f-driver-c2:first .input-47').eq(0).val();
						var drE = driversListForCalc.eq(i).find('.f-driver-c2:first .input-47').eq(1).val();
						drA = parseInt(drA);
						drE = parseInt(drE);
						if (drA < 22) drAId = '18-21';
						else if (drA <= 28) drAId = '22-28';
						else if (drA <= 35) drAId = '29-35';
						else if (drA <= 45) drAId = '36-45';
						else
						drAId = 'm45';

						if (drE <= 1) drEid = '0-1';
						else if (drE == 2) drEid = '2';
						else if (drE <= 5) drEid = '3-5';
						else if (drE <= 10) drEid = '6-10';
						else if ((drE <= 20)) drEid = '11-20';
						else
						drEid = 'm20';
						//					alert(drAId+' | '+drEid)
						var kAgeTMP = xmlK.find("drAge>spb>" + countDrivers + ">c").filter(function () {
							return $(this).find('a').text() == drAId
						}).find('v').eq(0).text();
						if (parseFloat(kAgeTMP) > kAge) kAge = parseFloat(kAgeTMP);
						var kExpTMP = xmlK.find("drExp>spb>c").filter(function () {
							return $(this).find('a').text() == drEid
						}).find('v').eq(0).text();
						if (parseFloat(kExpTMP) > kExp) kExp = parseFloat(kExpTMP);
					}
				}
			} else {
				if (multiDrive) {
					kAge = parseFloat(xmlK.find('drAge>msc>M5>c').filter(function () {
						return $(this).find('a').text() == '18-21'
					}).find('v').eq(0).text());
					kExp = parseFloat(xmlK.find('drExp>msc>c').filter(function () {
						return $(this).find('a').text() == '0-1'
					}).find('v').eq(0).text());
				} else {
					var drA, drE;
					for (var i = 0; i < driversListForCalc.length; i++) {
						var drA = driversListForCalc.eq(i).find('.f-driver-c2:first .input-47').eq(0).val();
						var drE = driversListForCalc.eq(i).find('.f-driver-c2:first .input-47').eq(1).val();
						drA = parseInt(drA);
						drE = parseInt(drE);
						if (drA < 22) drAId = '18-21';
						else if (drA < 24) drAId = '22-23';
						else if (drA < 29) drAId = '24-28';
						else if (drA < 36) drAId = '29-35';
						else if (drA < 46) drAId = '36-45';
						else
						drAId = 'm45';

						if (drE <= 1) drEid = '0-1';
						else if (drE == 2) drEid = '2';
						else if (drE <= 5) drEid = '3-5';
						else if (drE <= 10) drEid = '6-10';
						else if ((drE <= 20)) drEid = '11-20';
						else
						drEid = 'm20';

						var kAgeTMP = xmlK.find("drAge>msc>" + countDrivers + ">c").filter(function () {
							return $(this).find('a').text() == drAId
						}).find('v').eq(0).text();
						if (parseFloat(kAgeTMP) > kAge) kAge = parseFloat(kAgeTMP);
						var kExpTMP = xmlK.find("drExp>msc>c").filter(function () {
							return $(this).find('a').text() == drEid
						}).find('v').eq(0).text();
						if (parseFloat(kExpTMP) > kExp) kExp = parseFloat(kExpTMP);
					}
				}
			}
		} catch (ee) {
			alert(ee)
		}
		//		alert('4bt='+bt+'kAge'+kAge+'kExp='+kExp+'fr='+fr+'malus='+malus+'stoa='+stoa+'helm='+helm+'oplata='+oplata+'\nergoprice='+ERGOInfo.price);
		try {
			var malus = $('#noKaskoPayment:checked').length == 1 ? 0.9 : 1;

			var helm = $('#rightHelm:checked').length == 1 ? parseFloat(xmlK.find('rightHelm>' + city).eq(0).text()) : 1;

			//	СТОА
			var stoa = 1;
			var stoaInput = $('input:checked').filter('[name="sto"]').eq(0).val();
			if (city == 'msc') {
				switch (stoaInput) {
				case '0':
					stoa = parseFloat(xmlK.find('STOA>msc>c1').eq(0).text());
					break;
				case '1':
					stoa = parseFloat(xmlK.find('STOA>msc>c2').eq(0).text());
					break;
				case '3':
					stoa = $('#guarantee').attr('checked') ? parseFloat(xmlK.find('STOA>msc>c1').eq(0).text()) : parseFloat(xmlK.find('STOA>msc>c3').eq(0).text())
					break;
				case '4':
					stoa = parseFloat(xmlK.find('STOA>msc>c4').eq(0).text());
					break
				}
			} else {
				switch (stoaInput) {
				case '0':
					stoa = parseFloat(xmlK.find('STOA>spb>c1').eq(0).text());
					break;
				case '1':
					stoa = parseFloat(xmlK.find('STOA>spb>c2').eq(0).text());
					break;
				case '3':
					stoa = $('#guarantee').attr('checked') ? parseFloat(xmlK.find('STOA>spb>c1').eq(0).text()) : parseFloat(xmlK.find('STOA>spb>c3').eq(0).text())
					break;
					//			case '4':stoa=parseFloat(xmlK.find('STOA>spb>c4').eq(0).text());break
				}
			}
			oplata = xmlK.find('oplata>' + city);
			switch ($('input:checked').filter('[name="oplata"]').val()) {
			case '0':
				oplata = parseFloat(oplata.find('c0').text());
				break;
			case '1':
				oplata = parseFloat(oplata.find('c2').text());
				break;
			case '2':
				oplata = parseFloat(oplata.find('c4').text());
				break;
			case '3':
				oplata = parseFloat(oplata.find('c4').text());
				break;
			}

			ergoPrice = parseInt(price) * kAge * kExp * fr * bt / 100 * malus * stoa * helm * oplata;
			var discount = (100 - parseFloat($('#sk4').text())) / 100;
			ergoPriceDiscount = ergoPrice * discount;
			ERGOInfo.price = ergoPrice;
			if (ERGOInfo.price < parseInt(price) * 0.025) ERGOInfo.price = parseInt(price) * 0.025;
			ERGOInfo.discountPrice = ergoPriceDiscount;
			ERGOInfo.notes = ERGONotes;
			ERGOInfo.rating = 3;
			ERGOInfo.notesSpecial += "Размер франшизы " + addSpaces(ERGOInfo.realFr.toString()) + " руб.<br>";
			ERGOInfo.notesToDisplay.push("<span style='margin:0px; padding:0px; margin-left:24px;; position:relative; top:5px;'>Франшиза: " + addSpaces(ERGOInfo.realFr.toString()) + " руб.</span><br>");
			ERGOInfo.notesSpecial = 'Особенности расчета страховой компании Эрго Русь:<br>' + ERGOInfo.notesSpecial;
		} catch (ee) {
			alert(ee)
		};
	} else { // Юридические лица
		// базовый тариф
		var age = parseInt(carAge.replace('carAge', ''));
		if (age > 11) age = 11;

		if (rus) {
			bt = xmlK.find('juristic>bt>rus>p').filter(function () {
				return parseInt($(this).find('v:first').text()) > parseInt(price)
			}).first();
			if (bt.length == 0) bt = xmlK.find('juristic>bt>rus>p').last();
			bt = parseFloat(bt.find('a' + age).eq(0).text());
		} else {
			bt = xmlK.find('juristic>bt>ext>p').filter(function () {
				return parseInt($(this).find('v:first').text()) > parseInt(price)
			}).first();
			if (bt.length == 0) bt = xmlK.find('juristic>bt>ext>p').last();
			bt = parseFloat(bt.find('a' + age).eq(0).text());
		}
		var ageExp = 100;
		var ageMin = 100;
		var expMin = 100;
		if (multiDrive) ageExp = parseFloat(xmlK.find('juristic>multiDrive>c0').text());
		else {
			for (var i = 0; i < driversListForCalc.length; i++) {
				var drA = driversListForCalc.eq(i).find('.f-driver-c2:first .input-47').eq(0).val();
				var drE = driversListForCalc.eq(i).find('.f-driver-c2:first .input-47').eq(1).val();
				drA = parseInt(drA);
				drE = parseInt(drE);
				if (ageMin > drA) ageMin = drA;
				if (expMin < drE) expMin = drE;
			}
			if (expMin >= 5 && ageMin >= 28) ageExp = parseFloat(xmlK.find('juristic>multiDrive>c2').text());
			else if (expMin >= 2 && ageMin >= 23) ageExp = parseFloat(xmlK.find('juristic>multiDrive>c1').text());
			else ageExp = parseFloat(xmlK.find('juristic>multiDrive>c0').text());
		}

		oplata = xmlK.find('juristic>oplata');
		switch ($('input:checked').filter('[name="oplata"]').val()) {
		case '0':
			oplata = parseFloat(oplata.find('c1').text());
			break;
		case '1':
			oplata = parseFloat(oplata.find('c2').text());
			break;
		case '2':
			oplata = parseFloat(oplata.find('c4').text());
			break;
		case '3':
			oplata = parseFloat(oplata.find('c4').text());
			break;
		}
		if (!rus) { // Франшиза для иностранных ТС
			fr = xmlK.find("juristic>fr>Ext>p>v").filter(function () {
				return parseInt($(this).text()) >= parseInt(price)
			}).first().parent();
			if (fr.length == 0) fr = xmlK.find("juristic>fr>Ext>p>v").filter(function () {
				return $(this).text() == '*';
			}).parent();
			fr = fr.find('c').filter(function () {
				return parseInt($(this).find('p').text()) <= selectedFr;
			}).last();
			if (fr.length == 1) {
				ERGOInfo.realFr = parseInt(fr.find('p').eq(0).text());
				fr = parseFloat(fr.find('v').text());
			} else {
				ERGOInfo.realFr = 0;
				fr = 1;
			}
		} else { // Франшиза для отечественных ТС
			fr = xmlK.find('juristic>fr>rus>c').filter(function () {
				return parseInt($(this).find('p').text()) <= selectedFr;
			}).last();
			if (fr.length == 1) {
				ERGOInfo.realFr = parseInt(fr.find('p').eq(0).text());
				fr = parseFloat(fr.find('v').text());
			} else {
				ERGOInfo.realFr = 0;
				fr = 1;
			}
		}
		ergoPrice = parseInt(price) * bt / 100 * ageExp * oplata * fr //*fr*malus*stoa*helm;
		var discount = (100 - parseFloat($('#sk4').text())) / 100;
		ERGOInfo.price = ergoPrice;
		if (ERGOInfo.price < parseInt(price) * 0.025) ERGOInfo.price = parseInt(price) * 0.025;
		ERGOInfo.discountPrice = ergoPrice * discount;
		//		alert('bt='+bt+'kAge'+kAge+'kExp='+kExp+'fr='+fr+'malus='+malus+'stoa='+stoa+'helm='+helm+'oplata='+oplata+'\nergoprice='+ERGOInfo.price);
		ERGOInfo.notes = ERGONotes;
		ERGOInfo.rating = 3;
		ERGOInfo.notesSpecial += "Размер франшизы " + addSpaces(ERGOInfo.realFr.toString()) + " руб.<br>";
		ERGOInfo.notesToDisplay.push("<span style='margin:0px; padding:0px; margin-left:24px;; position:relative; top:5px;'>Франшиза: " + addSpaces(ERGOInfo.realFr.toString()) + " руб.</span><br>");
		ERGOInfo.notesSpecial = 'Особенности расчета страховой компании Эрго Русь:<br>' + ERGOInfo.notesSpecial;
	}
	if (priceChanged) {
		var frArr;
		if ($("#naturalPerson").attr('checked')) if (!rus) frArr = [3000, 6000, 9000, 12000, 15000, 30000, 45000, 60000, 90000];
		else
		frArr = [3000, 6000, 9000, 12000, 15000];
		else {
			if (parseInt(price) <= 350000) frArr = [6000, 9000, 12000];
			else if (parseInt(price) <= 1200000) frArr = [6000, 9000, 12000, 15000, 30000];
			else if (parseInt(price) <= 1800000) frArr = [6000, 9000, 12000, 15000, 30000, 45000, 60000, 90000];
			else
			frArr = [9000, 12000, 15000, 30000, 45000, 60000, 90000];
		}
		ERGOInfo.frArray = new Array(0);
		for (var i = 1; i <= frArr.length; i++) {
			var frImg = {
				value: null,
				image: null
			}
			if ((parseInt(price) / 100 * i) <= (slider2.maxVal + 1)) {
				try {
					frImg.value = frArr[i - 1];
					frImg.image = $("<img src='red.png' title='Франшиза " + addSpaces(frImg.value.toString()) + " руб. для страховой компании Эрго Русь'>");
					ERGOInfo.frArray.push(frImg);
				} catch (eee) {
					alert('err=' + eee)
				};
			}
		}
		for (var i = 0; i < ERGOInfo.frArray.length; i++) {
			var fromLeft = parseInt(ERGOInfo.frArray[i].value / slider2.maxVal * slider2.width);
			ERGOInfo.frArray[i].image.css("position", "absolute").css("left", fromLeft + "px").css("top", "0px").click(function () {
				$(this).parent().click();
			}).focus(function () {
				$(this).blur()
			}).appendTo($("#barsliderDiv1").eq(0));
			//				ERGOInfo.frArray[i].image.css("position","absolute").css("left",fromLeft+"px").css("top","0px").click(function(){$(this).parent().click();}).focus(function(){$(this).blur()}).clone().appendTo($("#barsliderDiv2").eq(0));
		}
	}
	counterCasco();
}